{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 14.3 用于预训练词嵌入的数据集"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 14.3.3 中心词和上下文词的提取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_centers_and_contexts(corpus, max_window_size):\n",
    "    \"\"\"返回跳元模型中的中心词和上下文词\"\"\"\n",
    "    centers, contexts = [], []\n",
    "    for line in corpus:\n",
    "        if len(line) < 2:\n",
    "            continue\n",
    "        centers += line\n",
    "        for i in range(len(line)):  # 上下文窗口中间\"i\"\n",
    "            window_size = random.randint(1, max_window_size)\n",
    "            indices = list(range(max(0, i - window_size),\n",
    "                                 min(len(line), i + 1 + window_size)))\n",
    "            # 从上下文词中排除中心词\n",
    "            indices.remove(i)\n",
    "            contexts.append([line[idx] for idx in indices])\n",
    "    return centers, contexts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dataset [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]\n",
      "center 0 has contexts [1, 2]\n",
      "center 1 has contexts [0, 2, 3]\n",
      "center 2 has contexts [0, 1, 3, 4]\n",
      "center 3 has contexts [1, 2, 4, 5]\n",
      "center 4 has contexts [3, 5]\n",
      "center 5 has contexts [4, 6]\n",
      "center 6 has contexts [5]\n",
      "center 7 has contexts [8, 9]\n",
      "center 8 has contexts [7, 9]\n",
      "center 9 has contexts [8]\n"
     ]
    }
   ],
   "source": [
    "tiny_dataset = [list(range(7)), list(range(7, 10))]\n",
    "print('dataset', tiny_dataset)\n",
    "for center, context in zip(*get_centers_and_contexts(tiny_dataset, 2)):\n",
    "    print('center', center, 'has contexts', context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
